<template>
  <!-- 荣誉记录 -->
  <base-breadcrumb :title="$route.meta.title">
    <!-- 搜索 -->
    <searchData ref="searchData" :searchData="searchArr" @search="search"></searchData>
    <!-- 表格 -->
    <a-card :bordered="false">
      <!-- <title-name :title="$route.meta.title"></title-name> -->
      <div class="mb12">
        <a-button v-btnPermission="'lu_0017_add_01'" icon="plus" type="primary" @click="handleManage(2)">新增</a-button>
        <ExcelImportButton
          v-btnPermission="'lu_0017_imp_05'"
          ref="excelImportButton"
          class="ml12"
          icon="import"
          readAll
          :rowIndex="2"
          :loading="loadingTwo"
          :sheetOptions="{defval:''}"
          @handleSubmit="handleSubmit"
        />
        <excel
          v-btnPermission="'lu_0017_exp_06'"
          class="ml12"
          ref="exportAll"
          fileName="荣誉记录"
          is-click-generate="false"
        >
          <a-button type="primary" icon="download" :loading="loading" slot="excelBtn" @click="exportAll">导出</a-button>
        </excel>
        <export-mould
          v-btnPermission="'lu_0017_imp_05'"
          style="margin-left: 5px"
          templateCode="西南公司荣誉台帐（工会）.xlsx"
          icon="cloud-download"
        ></export-mould>
      </div>
      <!-- 表格 -->
      <list-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :request="loadData"
        :alert="true"
        show-size-changer
        show-quick-jumper
        showPagination="auto"
      >
        <template slot="actions" slot-scope="text, record">
          <MoreButton>
          <a v-btnPermission="'lu_0017_loo_04'" @click="handleManage(0, record)">查看</a>
          <a v-btnPermission="'lu_0017_edi_02'" @click="handleManage(1, record)">编辑</a>
          <a v-btnPermission="'lu_0017_del_03'" class="del_btn" @click="handleRemove(record.id)">删除</a>
          </MoreButton>
        </template>
      </list-table>
    </a-card>
  </base-breadcrumb>
</template>

<script>
import { STable } from '@/components' // 表格
import { honorRecord } from '@/api/union/workersCongress' // api
import Selector from '@/components/Select/Selector'
import ExportMould from '@/components/ExportMould'
import BasePage from '@/views/basePage' // 基础配置

const searchArr = [
  // 搜索框
  {
    name: '获奖单位/个人',
    type: 'input',
    value: 'unitName',
  },
  {
    name: '获奖性质',
    valueKey: 'typeId',
    type: Selector,
    selectType: '5',
    urlType: 'union',
  },
  {
    name: '荣誉名称',
    type: 'input',
    value: 'honorName',
  },
  {
    name: '授奖时间',
    type: 'dateRange',
    value: 'time',
    attr: {
      rangeFormat: ['startTime', 'endTime'],
    },
  },
  {
    name: '表彰文号',
    type: 'input',
    value: 'commendationNumber',
  },
]
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    },
  },
  {
    title: '获奖单位/个人',
    ellipsis: true,
    dataIndex: 'unitName',
    render: (text, record, index) => {
      // return arguments[1].typeCode === '0' ? arguments[1].name : arguments[1].unitName;

      return (
        arguments[1].typeCode === '0' ? 
        <div
          dangerouslySetInnerHTML={{
            __html: `${<a-tooltip title={arguments[1].name} ><span class="ellipsis-span">{arguments[1].name}</span></a-tooltip>}`,
          }}
        ></div>
        :
        <div
          dangerouslySetInnerHTML={{
            __html: `${<a-tooltip title={arguments[1].unitName} ><span class="ellipsis-span">{arguments[1].unitName}</span></a-tooltip>}`,
          }}
        ></div>
      )
    }
  },
  {
    title: '获奖性质',
    ellipsis: true,
    dataIndex: 'typeName',
  },
  {
    title: '荣誉名称',
    ellipsis: true,
    dataIndex: 'honorName',
  },
  {
    title: '颁布单位',
    ellipsis: true,
    dataIndex: 'awardUnit',
  },
  {
    title: '授奖时间',
    ellipsis: true,
    dataIndex: 'awardWinningTime',
  },
  {
    title: '表彰文号',
    dataIndex: 'commendationNumber',
    ellipsis: true,
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '180px',
    align: 'center',
    scopedSlots: { customRender: 'actions' },
  },
]
export default {
    name:'a'+Date.now(),
  extends: new BasePage(),
  components: {
    STable,
    ExportMould,
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      queryParam: {}, // 查询参数
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, { query: this.queryParam })
        return honorRecord.getList(requestParameters).then((res) => {
          return res
        })
      }, // 加载数据方法 必须为 Promise 对象
      removeApi: honorRecord, // api
      loading: false, // 导出loading
      loadingTwo: false, // 导入loading
      position: '', // 岗位
      importCheck: {
        '获奖单位（集体）': 'unitName',
        荣誉名称: 'honorName',
        荣誉级别: 'levelName',
        颁发单位: 'awardUnit',
        授奖时间: 'awardWinningTime',
        表彰文号: 'commendationNumber',
        备注: 'content',
        电话: 'phone',
      },
    }
  },
  mounted() {
    this.position = this.$currentPost()?.postCode
    this.$refs.exportAll.tableToExcelFile(this.$refs.table, 0)
  },
  methods: {
    /**
     * 导入
     */
    handleSubmit(e) {
      console.log(e)
      let that = this
      let form = []
      for (let m in e) {
        for (let index in e[m]) {
          let keys = e[m][index]
          let listItem = {}
          console.log(keys)
          // 校验excel的表头数量
          if (Object.keys(keys)?.length === 7) {
            // 校验excel的表头字段
            for (let i in this.importCheck) {
              let item = this.importCheck[i]
              if (!keys[i] && (!Object.keys(keys).includes(i) && (m == 0 && item == 'unitName') && (m == 1 && item == 'phone'))) {
                this.$message.warning(`${i}缺失`)
                return
              } else {
                listItem[item] = keys[i]
              }
            }
            listItem['typeName'] = ['集体','个体'][m]
            form.push(listItem)
          } else {
            this.$message.warning('数据不完整')
            return
          }
        }
      }

      // 发送请求
      that.loadingTwo = true
      honorRecord
        .createBatch(form)
        .then(() => {
          that.loadingTwo = false
          that.$message.success('导入成功！')
          that.$refs.table.loadData()
        })
        .catch(() => {
          that.loadingTwo = false
        })
    },
    /**
     * 导出
     */
    exportAll() {
      this.loading = true
      honorRecord
        .getAllList(Object.assign({}, this.$refs.searchData.form.getFieldsValue()))
        .then((res) => {
          this.loading = false
          if(res.data?.length > 0){
            res.data.forEach((item, index) => {
              item.index = index + 1
              item.unitName = item.name ? item.name : item.unitName
            })
            this.$refs.exportAll.setDataAndGenerate(res.data)
            this.$message.success('导出成功')
          }else{
            this.$message.warning('没有数据可以导出')
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    /**
     * 搜索
     */
    search(value) {
      value && (this.queryParam = value)
      this.$refs.table.refresh(true)
    },
    /**
     * 操作栏
     */
    handleManage(type, record) {
      let query = {
        editModel: type,
      }
      if (record && record.id) {
        query.id = record.id
      }
      this.$router.push({
        name: '/union/bestHonor/honorRecordEdit',
        query,
      })
    },
  },
}
</script>
